package controller

import (
	"context"
	"github.com/RaymondCode/simple-demo/config"
	"github.com/RaymondCode/simple-demo/entity/myerr"
	"github.com/RaymondCode/simple-demo/entity/param"
	"github.com/RaymondCode/simple-demo/entity/response"
	"github.com/RaymondCode/simple-demo/middleware"
	serviceimpl "github.com/RaymondCode/simple-demo/service/impl"
	"github.com/RaymondCode/simple-demo/util/webutil"
	"github.com/cloudwego/hertz/pkg/app"
	"net/http"
	"strconv"
	"time"
)

func MessageAction(ctx context.Context, c *app.RequestContext) {
	var messageParam param.Message
	userId, err := strconv.Atoi(middleware.ThreadLocal.Get().(map[string]string)[config.Config.ThreadLocal.Keys.UserId])
	if err != nil {
		c.JSON(http.StatusBadRequest, response.SystemError)
		return
	}
	messageParam.UserId = userId
	messageParam.ToUserId, err = strconv.Atoi(c.Query("to_user_id"))
	messageParam.Content = c.Query("content")
	messageParam.ActionType, err = strconv.Atoi(c.Query("action_type"))
	messageParam.CreateTime = time.Now()
	if messageParam.ActionType != 1 {
		c.JSON(http.StatusBadRequest, response.ArgumentError(myerr.ArgumentInvalid(webutil.GetValidMsg(err, messageParam))))
		return
	}
	err = serviceimpl.NewMessageService().SendMessage(messageParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, response.SystemError)
		return
	}
	c.JSON(http.StatusOK, response.Ok)
}

func MessageChat(ctx context.Context, c *app.RequestContext) {
	var messageParam param.Message
	userId, err := strconv.Atoi(middleware.ThreadLocal.Get().(map[string]string)[config.Config.ThreadLocal.Keys.UserId])
	if err != nil {
		c.JSON(http.StatusBadRequest, response.SystemError)
		return
	}
	messageParam.UserId = userId
	messageParam.ToUserId, err = strconv.Atoi(c.Query("to_user_id"))
	list, err := serviceimpl.NewMessageService().MessageList(messageParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, response.SystemError)
		return
	}
	c.JSON(http.StatusOK, response.MessageList{
		Response:    response.Ok,
		MessageList: *list,
	})
}
